package com.haoshuang.zhouzhoubang.wxapi;

/**
 * Copyright (c) 山东六牛网络科技有限公司 https://liuniukeji.com
 *
 * @Description
 * @Author 你真好看
 * @Date 2018年12月01日 11:29:53
 * @CreateBy Android Studio
 */

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.haoshuang.zhouzhoubang.MyApp;
import com.haoshuang.zhouzhoubang.R;
import com.haoshuang.zhouzhoubang.config.Config;
import com.haoshuang.zhouzhoubang.model.event.WechatPaySuccessEvent;
import com.haoshuang.zhouzhoubang.utils.Event;
import com.haoshuang.zhouzhoubang.utils.PreferenceUtils;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";

    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pay_result);
        api = WXAPIFactory.createWXAPI(this, Config.WX_ID);
        api.handleIntent(getIntent(), this);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        // baseResp.state = "diandi_wx_login";
        Log.e("WXPay", baseResp.toString());
        switch (baseResp.errCode) {

            case -2:
                Toast.makeText(MyApp.Companion.getInstance(), "支付取消", Toast.LENGTH_SHORT).show();
                // ToastUtils.showShort("支付取消");
                finish();
                break;
            case 0:
                // ToastUtils.showShort("支付成功");
                Toast.makeText(MyApp.Companion.getInstance(), "支付成功", Toast.LENGTH_SHORT).show();
                // MessageEvent messageEvent = new MessageEvent(Constants.PAYSUCESS, "支付成功");
                String type = PreferenceUtils.getString("Wxpay");
                //  String  type= "1";
                if (type.equals("0")) {
                    EventBus.getDefault().post(new Event(8002, ""));
                } else if (type.equals("1")) {
                    EventBus.getDefault().post(new Event(8003, ""));
                } else if (type.equals("2")) {
                    EventBus.getDefault().post(new Event(8004, ""));
                } else if (type.equals("3")) {
                    EventBus.getDefault().post(new Event(8005, ""));
                } else if (type.equals("4")) {
                    EventBus.getDefault().post(new Event(8006, ""));
                } else if (type.equals("5")) {
                    EventBus.getDefault().post(new Event(80111, ""));
                } else if (type.equals("6")) {
                    EventBus.getDefault().post(new Event(80112, ""));
                } else if (type.equals("7")) {
                    EventBus.getDefault().post(new Event(80113, ""));
                } else if (type.equals("8")) {
                    EventBus.getDefault().post(new Event(80114, ""));
                } else if (type.equals("9")) {
                    EventBus.getDefault().post(new Event(80115, ""));
                } else if (type.equals("10")){
                    LiveEventBus.get(WechatPaySuccessEvent.class).post(WechatPaySuccessEvent.INSTANCE);
                    // EventBus.getDefault().post(new Event(8000,""));
                }
//                if (ActivityUtils.isActivityExistsInStack(BondNewActivity3.class)) {
//                    ActivityUtils.finishActivity(BondNewActivity3.class);
//                }
//                if (ActivityUtils.isActivityExistsInStack(BondTdNew3Activity.class)) {
//                    ActivityUtils.finishActivity(BondTdNew3Activity.class);
//                }

                this.finish();
                break;
            case 1:
                // ToastUtils.showShort("支付失败");
                Toast.makeText(MyApp.Companion.getInstance(), "支付失败", Toast.LENGTH_SHORT).show();
                finish();
                break;
        }
    }

    private void getAccessToken(String code) {

        //获取授权
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=")
                .append("wxa7bd150a209f76f9")
                .append("&secret=")
                .append("72ea138f690f7946a54f523356164156")
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");
        Log.d("urlurl", loginUrl.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(loginUrl.toString())
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("fan12", "onFailure: ");
                // mProgressDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseInfo = response.body().string();
                Log.d("fan12", "onResponse: " + responseInfo);
                String access = null;
                String openId = null;
                try {
                    JSONObject jsonObject = new JSONObject(responseInfo);
                    access = jsonObject.getString("access_token");
                    openId = jsonObject.getString("openid");
                    Log.e("WXPay", "access: " + access);
                    Log.e("WXPay", "openId: " + openId);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // getUserInfo(access, openId);
            }
        });
    }
}